package dbs

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	_ "github.com/go-sql-driver/mysql"
	"github.com/xormplus/core"
	"github.com/xormplus/xorm"
	"os"
	"time"
)

type JsonTime time.Time

func (j JsonTime) MarshalJSON() ([]byte, error) {
	if time.Time(j).Unix() == -62135596800 {
		return []byte(`null`), nil
	}
	return []byte(`"` + time.Time(j).Format("2006-01-02 15:04:05") + `"`), nil
}

func (j JsonTime) UnmarshalJSON(b []byte) error {
	return json.Unmarshal(b, &j)
}

func DB(dbAddress string) (*xorm.Engine, error) {
	dbAdd := dbAddress
	if dbAddress == "" {
		dbAdd = beego.AppConfig.String("FYDBAddress")
	}

	fmt.Println(dbAdd)
	var result *xorm.Engine = nil
	if db, err := xorm.NewEngine("mysql", dbAdd); err != nil {
		return nil, err
	} else {
		if err = db.DB().Ping(); err != nil {
			return nil, err
		}

		if tables, err := db.DBMetas(); err != nil {
			beego.Emergency(err)
			return nil, err
		} else {
			if len(tables) == 0 {
				beego.Warning("initialize db tables")
				// db.ImportFile("./conf/data/user.sql")
			}
		}

		err = db.RegisterSqlTemplate(xorm.Pongo2("./sql", ".stpl"))
		if err != nil {
			beego.Emergency(err)
			return nil, err
		}
		err = db.StartFSWatcher()
		if err != nil {
			beego.Emergency(err)
			return nil, err
		}
		db.TZLocation, _ = time.LoadLocation("Asia/Shanghai")

		f, err := os.Create("logs/sql.log")
		if err != nil {
			beego.Emergency(err)
			println(err.Error())
		}
		db.SetMaxIdleConns(30)
		db.SetMaxOpenConns(100)
		db.SetLogger(xorm.NewSimpleLogger(f))
		db.ShowSQL(true)
		db.Logger().SetLevel(core.LOG_DEBUG)
		result = db
	}

	return result, nil
}

var instance_fy *xorm.Engine = nil
var instance_admin *xorm.Engine = nil

func FYDB() (*xorm.Engine, error) {
	var err error
	if instance_fy == nil {
		instance_fy, err = DB(beego.AppConfig.String("FYDBAddress"))
	}
	return instance_fy, err
}

func AdminDB() (*xorm.Engine, error) {
	var err error
	if instance_admin == nil {
		instance_admin, err = DB(beego.AppConfig.String("AdminDBAddress"))

	}
	return instance_admin, err
}
